<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-管圈颜色`"
		width="500px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="管圈类型" prop="typeId">
						<el-select v-model="ruleForm.typeId" :disabled="!!defaultTypeCode" class="width-100-percent" placeholder="管圈类型">
							<el-option
								v-for="item in typeList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="编号">
						<el-input v-model="ruleForm.code" placeholder="无自定义需求时，可不填写，系统将自动生成" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="名称" />
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="重量" prop="weight">
						<el-input v-model="ruleForm.weight" placeholder="重量" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-button size="mini" icon="el-icon-plus" class="margin-bottom-4" @click="onAddBtn">添加</el-button>
			<jk-table border :data="ruleForm.spinWeightItemList" :height="260">
				<vxe-column title="机台锭数" align="right" field="spinCount" :min-width="100">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.spinCount" size="mini" placeholder="机台锭数"></jk-number-input>
					</template>
				</vxe-column>
				<vxe-column title="总管重(kg)" align="right" field="weight" :min-width="100">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.weight" size="mini" placeholder="总管重(kg)"></jk-number-input>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" field="shiftName" :width="70">
					<template slot-scope="scope">
						<div class="item-gap"><el-button size="mini" icon="el-icon-delete" @click="onDeleteBtn(scope.rowIndex)"></el-button></div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        spinTubeColorCreate,
        spinTubeColorUpdate,
        spinTubeColorGet
    } from '../../../api/basicData/tubeColor';
    import { systemBusinessDictPage } from '../../../api/basicData/businessDict';
    export default {
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                typeList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    code: '',
                    name: '',
                    colorValue: '',
                    typeId: null,
                    spinWeightItemList: [],
                    weight: null
                },
                rules: {
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    colorValue: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }]
                },
                defaultRowItem: {
                    spinCount: 0,
                    weight: 0
                }
            };
        },
        methods: {
            onDeleteBtn(index) {
                this.ruleForm.spinWeightItemList.splice(index, 1);
            },
            onAddBtn() {
                this.ruleForm.spinWeightItemList.push(JSON.parse(JSON.stringify(this.defaultRowItem)));
            },
            onBlurCode() {
                this.$set(this.ruleForm, 'code', this.ruleForm.code.toUpperCase());
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                const typeItem = this.typeList.find(x => x.id === params.typeId) || {};
                params.typeCode = typeItem.code;
                params.typeName = typeItem.name;
                params.code = params.code.toUpperCase();
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? spinTubeColorCreate : spinTubeColorUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinTubeColorGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res;
                        resData.spinWeightItemList = resData.spinWeightItemList || [];
                        this.ruleForm = resData;
                    }
                });
            },
            getTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'GQ_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.typeList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                console.log(this.defaultTypeCode, 'this.defaultTypeCode');

                this.showLoading = true;
                await this.getTypeListRequest();
                if (this.defaultTypeCode) {
                    const item = this.typeList.find(x => x.code === this.defaultTypeCode) || {};
                    this.$set(this.ruleForm, 'typeId', item.id);
                    this.$set(this.ruleForm, 'typeName', item.name);
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
